package com.cy.interfacetest.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;

import com.cy.interfacetest.R;
import com.cy.interfacetest.entity.AppInfo;
import com.cy.interfacetest.policyinterface.IPolicyManager;
import com.cy.interfacetest.policyinterface.impl.IPolicyManagerImpl;
import com.cy.interfacetest.proxy.ModuleProxy;
import com.cy.interfacetest.util.DeviceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import ga.mdm.PolicyManager;


@RequiresApi(api = Build.VERSION_CODES.N)
public class ConfigPolicyActivity extends BaseActivity {
    private ModuleProxy<IPolicyManager> proxy = new ModuleProxy<>();
    private IPolicyManager pm = proxy.getInstance(new IPolicyManagerImpl(PolicyManager.getInstance()));
    private static final String TAG = "ConfigPolicyActivity";
    private EditText whiteApp;
    private EditText blackList;
    private EditText ssid;
    private EditText mac;
    private EditText pwd;
    private EditText apnName;
    private EditText apnDescribe;
    private EditText uninstallWhileList;
    private EditText uninstallBlackList;
    private EditText runWhiteList;
    private EditText runBlackList;
    private String protocol;
    private EditText address;
    private EditText port;
    private EditText command;
    private TextView logView;

    Handler handler = new Handler();
    StringBuilder sb = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config_policy);
        setTitle("配置策略");
        logView = (TextView) findViewById(R.id.log);
        handler.post(() -> {
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
                String s = "";
                StringBuilder sb = new StringBuilder();
                while ((s = bufferedReader.readLine()) != null) {
                    sb.append(s + "\n");
                }
                logView.setText(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        // TODO: 2024/7/11  wifi
        ssid = findViewById(R.id.ssid);

        mac = findViewById(R.id.mac);

        pwd = findViewById(R.id.pwd);
        // TODO: 2024/7/25 apn 配置
        apnName = findViewById(R.id.apn_name);

        apnDescribe = findViewById(R.id.apn_describe);


        whiteApp = findViewById(R.id.whiteAppId);

        blackList = findViewById(R.id.blackAppId);

        uninstallWhileList = findViewById(R.id.uninstall_while_list);

        uninstallBlackList = findViewById(R.id.uninstall_black_list);

        runWhiteList = findViewById(R.id.run_white_list);

        runBlackList = findViewById(R.id.run_black_list);

        whiteApp.setOnClickListener(e -> checkApp(e));
        blackList.setOnClickListener(e -> checkApp(e));
        uninstallWhileList.setOnClickListener(e -> checkApp(e));
        uninstallBlackList.setOnClickListener(e -> checkApp(e));
        runWhiteList.setOnClickListener(e -> checkApp(e));
        runBlackList.setOnClickListener(e -> checkApp(e));

        address = (EditText) findViewById(R.id.address);

        port = (EditText) findViewById(R.id.port);

        Spinner spinner = findViewById(R.id.spinner);
        final String[] items = new String[]{"全部", "UDP", "TCP"};
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
        stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(stringArrayAdapter);


        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                protocol = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        command = (EditText) findViewById(R.id.command);

    }

    public void applyConfig(View view) {
        String config = "[{\"ssid\":\"" + ssid.getText().toString().trim() + "\",\"bssid\":\"" + mac.getText().toString().trim() + "\",\"pwd\":\"" + pwd.getText().toString().trim() + "\"}]";
        switchPassOrFailure(pm.setWlanConfiguration(config), view);
    }

    public void addApn(View view) {
        AtomicReference<String> apnInfo = new AtomicReference<>();
        pm.getApnList().stream().findFirst().ifPresent(e -> apnInfo.set(pm.getApnInfo(e)));
        try {
            JSONObject jsonObject = new JSONObject(apnInfo.get());
            jsonObject.putOpt("name", apnName.getText().toString().trim());
            jsonObject.putOpt("apn", apnDescribe.getText().toString().trim());
            Log.i(TAG, "addApn: " + jsonObject);
            switchPassOrFailure(pm.createApn(jsonObject.toString()) != -1, view);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setWhitelist(View view) {
        String app = whiteApp.getText().toString().trim();
        Toast.makeText(this, "设置白名单为：" + app, Toast.LENGTH_SHORT).show();
        switchPassOrFailure(pm.setAppInstallationPolicies(1, "".equals(app) ? null : new String[]{app}), view);
    }

    public void setBlacklist(View view) {
        String app = blackList.getText().toString().trim();
        app = "".equals(app) ? null : app;
        Toast.makeText(this, "设置黑名单为：" + app, Toast.LENGTH_SHORT).show();
        switchPassOrFailure(pm.setAppInstallationPolicies(0, "".equals(app) ? null : new String[]{app}), view);
    }

    /**
     * 卸载白名单
     *
     * @param view
     */
    public void uninstallWhilelist(View view) {
        Log.i(TAG, "uninstallWhilelist: ");
        String whileLIst = uninstallWhileList.getText().toString().trim();
        Toast.makeText(this, "设置卸载白名单为：" + whileLIst, Toast.LENGTH_SHORT).show();
        switchPassOrFailure(pm.setAppUninstallationPolicies(1, "".equals(whileLIst) ? null : new String[]{whileLIst}), view);
    }

    /**
     * 卸载黑名单
     *
     * @param view
     */
    public void uninstallBlackList(View view) {
        Log.i(TAG, "uninstallBlackList: ");
        String blackLIst = uninstallBlackList.getText().toString().trim();
        Toast.makeText(this, "设置卸载黑名单为：" + blackLIst, Toast.LENGTH_SHORT).show();
        switchPassOrFailure(pm.setAppUninstallationPolicies(0, "".equals(blackLIst) ? null : new String[]{blackLIst}), view);
    }

    // TODO: 2024/7/25 应用运行白名单
    public void RunWhiteList(View view) {
        String whiteLIst = runWhiteList.getText().toString().trim();
        Log.i(TAG, "RunWhiteList: " + whiteLIst);
        Toast.makeText(this, "应用运行白名单 ：" + whiteLIst, Toast.LENGTH_SHORT).show();

        switchPassOrFailure(pm.setRunAppPolicies(1, "".equals(whiteLIst) ? null : new String[]{whiteLIst}), view);
    }

    // TODO: 2024/7/25 应用运行黑名单
    public void RunBlackList(View view) {
        Log.i(TAG, "RunBlackList: ");
        String blackLIst = runBlackList.getText().toString().trim();
        Toast.makeText(this, "应用运行黑名单 ：" + blackLIst, Toast.LENGTH_SHORT).show();

        switchPassOrFailure(pm.setRunAppPolicies(0, "".equals(blackLIst) ? null : new String[]{blackLIst}), view);
    }

    public void checkApp(View view) {
        // TODO: 2024/7/28  如果不是EditText 直接return  有可能是父组件
        if (!(view instanceof EditText)) return;
        EditText text = (EditText) view;

        // TODO: 2024/7/29 去掉自己，否则可能会出现 无法打开问题，比如运行白名单 等。。。
        List<AppInfo> installApps = getInstallApps().stream().filter(AppInfo.notSelf).collect(Collectors.toList());

        AppInfo[] appInfos = installApps.toArray(new AppInfo[]{});
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择应用");
        ListView listView = new ListView(this);
        ArrayAdapter<AppInfo> adapter = new ArrayAdapter<AppInfo>(this, android.R.layout.simple_list_item_1, appInfos);
        listView.setAdapter(adapter);
        builder.setView(listView);
        final AlertDialog dialog = builder.create();
        dialog.show();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AppInfo appInfo = appInfos[position];
                text.setText(appInfo.getId());
                dialog.dismiss();
            }
        });
    }

    @Nullable
    private List<String> assembleAddr() {
        String ip = address.getText().toString().trim();
        String postStr = port.getText().toString().trim();

        if ("".equals(ip)) {
            Toast.makeText(this, "地址错误", Toast.LENGTH_SHORT).show();
            return null;
        }

        protocol = "全部".equals(protocol) ? " " : protocol;
        postStr = "".equals(postStr) ? " " : postStr;
        String ads = ip + "#" + protocol + "#" + postStr;
        List<String> addrList = new ArrayList<>();
        addrList.add(ads);
        return addrList;
    }

    private void printLog(String x, List<String> addrList) {
        String addr = x + addrList.get(0);
        logView.append(addr + "\n");
        proxy.setLog(sb); // TODO: 2024/11/7 将已经执行命令取回
        CharSequence text = logView.getText();
        logView.setText(text + sb.toString() + "\n\n");
        // TODO: 2024/11/7 追加写出
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)))) {
            bw.write(addr + "\n");
            bw.write(sb.toString() + "\n\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addNetworkAccess(View view) {
        List<String> addrList = assembleAddr();
        if (addrList == null) return;
        addNetworkAccessWhitelist(addrList, true);

        printLog("添加白名单：", addrList);
    }


    public void removeNetwork(View view) {
        List<String> addList = assembleAddr();
        removeNetworkAccessWhitelist(addList);
        printLog("删除白名单：", addList);
    }

    public void editCommand(View view) {
        String commandStr = command.getText().toString().trim();
        if ("".equals(commandStr)) {
            Toast.makeText(this, "命令不能为空！", Toast.LENGTH_LONG).show();
            return;
        }
        String s = pm.executeShellToSetIptables(commandStr);
        ArrayList<String> addrList = new ArrayList<>();
        addrList.add(commandStr);
        printLog("自定义命令：",addrList);

    }

   /* public boolean addNetworkAccessWhitelist(List<String> addrList, boolean isExistIpWHiteList) {

        if (DeviceUtil.isTY()) {
            pm.executeShellToSetIptables("-F");
            Log.d(TAG, "isTY -F");
        }else if (DeviceUtil.isAlpsX7()) {
            pm.executeShellToSetIptables("-A OUTPUT -j DROP");
            Log.d(TAG, "-A OUTPUT -j DROP");
        }
        for (String addr : addrList) {
            Log.d(TAG, "add WhiteList: " + addr);
            String ip = " ";
            String protocol = " ";
            String port = " ";
            if (addr.contains("#")) {
                String[] netStr = addr.split("#");
                ip = netStr[0];
                protocol = netStr[1];
                port = netStr[2];
            } else {
                ip = addr;
            }

            String iptableCommand;
            Log.d(TAG, "执行白名单: 手机型号" + Build.MODEL );
            if (isHNDDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -d " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-I OUTPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isAlpsX7()) {
//                iptables -I INPUT -s 14.215.177.38 -j ACCEPT
                iptableCommand = "-I OUTPUT -d " + ip + " -j ACCEPT";
            } else if (DeviceUtil.isP7()) {
                iptableCommand = "iptables -A OUTPUT -p all -s " + ip + " -j ACCEPT";
            } else if (DeviceUtil.isJiaSaiHonorDevice(mContext)) {
                Log.d(TAG, "addNetworkAccessWhitelist  isJSDevice : ");
//                iptableCommand = "iptables -I OUTPUT -d " + ip + " -j ACCEPT";
                iptableCommand = "iptables -I INPUT -s " + ip +" -j ACCEPT";
            } else if (isHWCDevice() || isWateDevice() || isZETDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -d " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-I OUTPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isKeDaComF3()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-I INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-I INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isDsMdt401()) {//iptables -A INPUT -s <IP地址> -j ACCEPT
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -A INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -A INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -A INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "iptables -A INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if(DeviceUtil.isTY()){
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-A INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-A INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-A INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-A INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            }  else {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            }
            //iptables -A INPUT -p tcp -s 91.108.56.141 --sport 443 -j DROP
            Log.d(TAG, "执行白名单: " + iptableCommand);
            // policyManager.executeShellToSetIptables(iptableCommand);
            try {
                String s = pm.executeShellToSetIptables(iptableCommand);
                Log.d(TAG, "add result ==   :" + s);
            } catch (Exception e) {
                Log.e(TAG, e);
                Log.d(TAG, "add result ==  e :" + e.toString());
                e.printStackTrace();
            }
        }

        if (!isExistIpWHiteList) {
            Log.d(TAG, "没有白名单，需要添加禁用: ");
            if (isHNDDevice() || isZETDevice() || isHWCDevice() || isWateDevice()) {
                try {
                    pm.executeShellToSetIptables("-A OUTPUT -j DROP");
                    Log.d(TAG, "-A OUTPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  001 e :" + e.toString());
                }
            } else if (DeviceUtil.isJiaSaiHonorDevice(mContext)) {
                String result = pm.executeShellToSetIptables("iptables -A INPUT -j DROP");
                Log.d(TAG, "addNetworkAccessWhitelist JS 禁用所有: " + result);
            } else if (DeviceUtil.isAlpsX7()) {
//                policyManager.executeShellToSetIptables("-A OUTPUT -j DROP");
//                NsLog.d(TAG, "-A OUTPUT -j DROP");
                return true;
            } else if (DeviceUtil.isP7()) {
                String result = pm.executeShellToSetIptables("iptables -A OUTPUT -p all  -j DROP");
                Log.d(TAG, "isP7 addNetworkAccessWhitelist JS isP7禁用所有: " + result);
            }  else if(DeviceUtil.isTY()){
                pm.executeShellToSetIptables("-A INPUT -j DROP");
                Log.d(TAG, "-A INPUT -j DROP");
            } else if (DeviceUtil.isKeDaComF3()) {
                try {
                    pm.executeShellToSetIptables("-A INPUT -j DROP");
                    Log.d(TAG, "-A INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  002 e :" + e.toString());
                }
            } else {
                try {
                    pm.executeShellToSetIptables("iptables -A INPUT -j DROP");
                    Log.d(TAG, "iptables -A INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  002 e :" + e.toString());
                }
            }
        }

        return true;
    }*/

    public boolean addNetworkAccessWhitelist(List<String> addrList, boolean isExistIpWHiteList) {

        if (DeviceUtil.isXJV9H9() || DeviceUtil.isDSJS2() || DeviceUtil.isDSJF5()) {
            try {
                String command = "iptables -P INPUT DROP";
                String s = pm.executeShellToSetIptables(command);
                Log.d(TAG, "iptables -P INPUT DROP execute result: " + s);
                command = "iptables -P OUTPUT ACCEPT";
                s = pm.executeShellToSetIptables(command);
                Log.d(TAG, "iptables -P OUTPUT ACCEPT execute result : " + s);
                command = "iptables -P FORWARD ACCEPT";
                s = pm.executeShellToSetIptables(command);
                Log.d(TAG, "iptables -P FORWARD ACCEPT execute result:" + s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (String addr : addrList) {
            Log.d(TAG, "add WhiteList==: " + addr);
            String ip = " ";
            String protocol = " ";
            String port = " ";
            if (addr.contains("#")) {
                String[] netStr = addr.split("#");
                ip = netStr[0];
                protocol = netStr[1];
                port = netStr[2];
            } else {
                ip = addr;
            }

            String iptableCommand = "";
            if (DeviceUtil.isZETDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -d " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-I OUTPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-I OUTPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isHXDevice() || DeviceUtil.isGXXDevice() || DeviceUtil.isM9() || DeviceUtil.isRuixinH2Device()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-I INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-I INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-I INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isMeiYaDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isDSJA8()) {
                pm.executeShellToSetIptables("iptables -F OUTPUT");
                pm.executeShellToSetIptables("iptables -P OUTPUT DROP");
                iptableCommand = "iptables -I OUTPUT -d " + ip + " -j ACCEPT";
            } else if (DeviceUtil.isXJV9H9() || DeviceUtil.isDSJS2() || DeviceUtil.isDSJF5()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -A INPUT -s " + ip + " -p all -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " -p all -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -I INPUT -s " + ip + " --sport " + port + " -p all -j ACCEPT";
                } else {
                    iptableCommand = "iptables -I INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -p all -j ACCEPT";
                }
            } else {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "iptables -D INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            }
            //iptables -A INPUT -p tcp -s 91.108.56.141 --sport 443 -j DROP
            try {
                Log.d(TAG, "iptableCommand: " + iptableCommand);
                pm.executeShellToSetIptables(iptableCommand);
            } catch (Exception e) {
                Log.d(TAG, "add == e :" + e.toString());
            }
        }

        if (!isExistIpWHiteList) {
            Log.d(TAG, "没有白名单，需要添加禁用: ");
            if (DeviceUtil.isZETDevice()) {
                try {
                    pm.executeShellToSetIptables("-A OUTPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  001 e :" + e.toString());
                }
            } else if (DeviceUtil.isRuixinH2Device()) {
                try {
                    pm.executeShellToSetIptables("ip6tables -A INPUT -j DROP");
                    pm.executeShellToSetIptables("-A INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  001 e :" + e.toString());
                }
            } else if (DeviceUtil.isHXDevice() || DeviceUtil.isGXXDevice() || DeviceUtil.isM9()) {
                try {
                    pm.executeShellToSetIptables("-A INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add  001 e :" + e.toString());
                }
            } else if (DeviceUtil.isXJV9H9() || DeviceUtil.isDSJS2() || DeviceUtil.isDSJF5()) {
                Log.d(TAG, "XJV9 no execute DROP");
            } else {
                try {
                    pm.executeShellToSetIptables("iptables -A INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "add 002 e :" + e.toString());
                }
            }
        }
        return true;
    }

    public void removeNetworkAccessWhitelist(List<String> addrList) {
        if (addrList == null || addrList.size() < 1) return;
        //判断是否还有其他策略，没有恢复访问网络


        if (DeviceUtil.isXJV9H9()) {
            String s = pm.executeShellToSetIptables("iptables -X");
            Log.d(TAG, "removeNetworkAccessWhitelist iptables -X result:" + s);
            s = pm.executeShellToSetIptables("iptables -F");
            Log.d(TAG, "removeNetworkAccessWhitelist iptables -F result:" + s);
            s = pm.executeShellToSetIptables("iptables -P INPUT ACCEPT");
            Log.d(TAG, "iptables -P INPUT ACCEPT: " + s);
            s = pm.executeShellToSetIptables("iptables -L -n");
            Log.d(TAG, "iptables -L -n result: " + s);

            pm.executeShellToSetIptables("iptables -P OUTPUT ACCEPT");
            pm.executeShellToSetIptables("iptables -P FORWARD ACCEPT");
            return;
        }

        boolean delSingleFlag = false;
        for (String addr : addrList) {
            Log.d(TAG, "remove WhiteList: " + addr);
            String ip = " ";
            String protocol = " ";
            String port = " ";
            if (addr.contains("#")) {
                String[] netStr = addr.split("#");
                ip = netStr[0];
                protocol = netStr[1];
                port = netStr[2];
            } else {
                ip = addr;
            }
            String iptableCommand;
            if (DeviceUtil.isZETDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D OUTPUT -d " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D OUTPUT -d " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-D OUTPUT -d " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-D OUTPUT -d " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isHXDevice()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-D INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "-D INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else if (DeviceUtil.isGXXDevice() || DeviceUtil.isM9()) {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "-D INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "-D INPUT -s " + ip + " -j ACCEPT";
                } else {
                    iptableCommand = "-D INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            } else {
                if (" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -s " + ip + " -j ACCEPT";
                } else if (!" ".equals(protocol) && " ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -p " + protocol + " -s " + ip + " -j ACCEPT";
                } else if (" ".equals(protocol) && !" ".equals(port)) {
                    iptableCommand = "iptables -D INPUT -s " + ip + " --sport " + port + " -j ACCEPT";
                } else {
                    iptableCommand = "iptables -D INPUT -p " + protocol + " -s " + ip + " --sport " + port + " -j ACCEPT";
                }
            }
            try {
                Log.d(TAG, "remove iptableCommand: " + iptableCommand);
                pm.executeShellToSetIptables(iptableCommand);
            } catch (Exception e) {
                Log.d(TAG, "remove e :" + e.toString());
            }
        }

        boolean delAllFlag = false;
        boolean isExistIpWhiteList = false; // TODO: 2024/11/5 没有其他白名单 全部删除
        if (!isExistIpWhiteList) {// TODO: 2024/11/5 如果有其他的白名单就不操作，如果没有其他白名单，就将所有网络恢复
            if (DeviceUtil.isZETDevice()) {
                try {
                    pm.executeShellToSetIptables("-D OUTPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "remove 01 e :" + e.toString());
                }
            } else if (DeviceUtil.isHXDevice() || DeviceUtil.isGXXDevice() || DeviceUtil.isM9()) {
                try {
                    pm.executeShellToSetIptables("-D INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "remove 01 e :" + e.toString());
                }
            } else {
                try {
                    pm.executeShellToSetIptables("iptables -D INPUT -j DROP");
                } catch (Exception e) {
                    Log.d(TAG, "remove 02 e :" + e.toString());
                }
            }
            Log.d(TAG, "最后一条，恢复上网");
        }

    }

}